package com.dayaokeji.imkitwrapper.init;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.provider.Settings;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.beetle.bauhinia.api.IMHttpAPI;
import com.beetle.bauhinia.api.types.Image;
import com.beetle.bauhinia.db.CustomerMessageDB;
import com.beetle.bauhinia.db.CustomerMessageHandler;
import com.beetle.bauhinia.db.GroupMessageDB;
import com.beetle.bauhinia.db.GroupMessageHandler;
import com.beetle.bauhinia.db.PeerMessageDB;
import com.beetle.bauhinia.db.PeerMessageHandler;
import com.beetle.bauhinia.db.SyncKeyHandler;
import com.beetle.bauhinia.tools.FileCache;
import com.beetle.bauhinia.tools.Outbox;
import com.beetle.im.IMService;
import com.dayaokeji.imkitwrapper.BuildConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * ********************************************************************
 * *  Created by Zeno on 2018/6/22
 * ********************************************************************
 * *  version 1.0
 * ********************************************************************
 * *  Copyright (C) dayaokeji.com 2018 -- 2020 All rights reserved.
 * ********************************************************************
 * * im 初始化
 * ********************************************************************
 */
public class ImKitWrapper {

    private final static String TAG = ImKitWrapper.class.getSimpleName();

    private ImKitWrapper(){}

    private static ImKitWrapper instance;
    private static IMService mIMService;

    public static ImKitWrapper getInstance() {
        if (instance == null) {
            synchronized (ImKitWrapper.class) {
                if (instance == null) {
                    instance = new ImKitWrapper();
                }
            }
        }
        return instance;
    }

    public static void setHeaderToken(String token) {
        IMHttpAPI.setHeaderToken(token);
    }

    /**
     * init im
     * @param context context
     */
    public static void init(Context context,String uid) {

        //可以在登录成功后，设置每个用户不同的消息存储目录
        FileCache fc = FileCache.getInstance();
        fc.setDir(context.getDir("cache_"+uid, Context.MODE_PRIVATE));

        PeerMessageDB db = PeerMessageDB.getInstance();
        db.setDir(context.getDir("peer_"+uid, Context.MODE_PRIVATE));
        GroupMessageDB groupDB = GroupMessageDB.getInstance();
        groupDB.setDir(context.getDir("group_"+uid, Context.MODE_PRIVATE));
        CustomerMessageDB csDB = CustomerMessageDB.getInstance();
        csDB.setDir(context.getDir("customer_service_"+uid, Context.MODE_PRIVATE));


    }


    public static void registerVieAnswerBroadcastReceiver(Context context, BroadcastReceiver receiver) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_VIE_ANSWER);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        LocalBroadcastManager.getInstance(context).registerReceiver(receiver, intentFilter);
    }

    public static void unRegisterVieAnswerBroadcastReceiver(Context context, BroadcastReceiver receiver) {
        LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver);
    }

    private static void connectionIm(Context context,String host, String apiUrl) {
        if (mIMService == null) {
            mIMService = IMService.getInstance();
        }
        IMHttpAPI.setAPIURL(apiUrl);

        mIMService.setHost(host);
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "set im host == "+host);
        }
        @SuppressLint("HardwareIds") String androidID = Settings.Secure.getString(context.getContentResolver(),
                Settings.Secure.ANDROID_ID);

        //设置设备唯一标识,用于多点登录时设备校验
        mIMService.setDeviceID(androidID);

        //监听网路状态变更
        mIMService.registerConnectivityChangeReceiver(context);

        mIMService.setPeerMessageHandler(PeerMessageHandler.getInstance());
        mIMService.setGroupMessageHandler(GroupMessageHandler.getInstance());
        mIMService.setCustomerMessageHandler(CustomerMessageHandler.getInstance());
    }

    /**
     * login im
     * @param sender
     * @param token
     */
    public static void login(Context context,long sender,String token,String host,String apiUrl) {
        connectionIm(context, host, apiUrl);

        Log.d(TAG,"sender == "+sender+" ------ token == "+token+" host == "+host+"  apiurl === "+apiUrl);

        PeerMessageHandler.getInstance().setUID(sender);
        GroupMessageHandler.getInstance().setUID(sender);
        IMHttpAPI.setToken(token);
        mIMService.setToken(token);

        SyncKeyHandler handler = new SyncKeyHandler(context, "sync_key");
        handler.load();

        HashMap<Long, Long> groupSyncKeys = handler.getSuperGroupSyncKeys();
        mIMService.clearSuperGroupSyncKeys();
        for (Map.Entry<Long, Long> e : groupSyncKeys.entrySet()) {
            mIMService.addSuperGroupSyncKey(e.getKey(), e.getValue());
            Log.i(TAG, "group id:" + e.getKey() + "sync key:" + e.getValue());
        }
        mIMService.setSyncKey(handler.getSyncKey());
        Log.i(TAG, "sync key:" + handler.getSyncKey());
        mIMService.setSyncKeyHandler(handler);

        mIMService.start();

    }

    public static void stopImService() {
        if (mIMService != null) {
            mIMService.setToken("");
            mIMService.setToken("");
            mIMService.stop();
        }
    }
}
